package com.eke.action.article;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import com.eke.bean.Article;
import com.eke.bean.ArticleType;
import com.eke.bean.QuestionFrom;
import com.eke.bean.Users;
import com.eke.service.ArticleService;
import com.eke.service.UserConcernService;
import com.eke.service.UsersService;
import com.jason.mvc.annotations.Ajax;
import com.jason.mvc.annotations.Namespace;
import com.jason.mvc.annotations.RequestMapping;
import com.jason.mvc.utils.ApplicationContext;

@Namespace("/article")
@Component("articleAction")
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class ArticleAction {
	@Resource
	private ArticleService articleService;
	@Resource
	private UsersService usersService;
	@Resource
	private UserConcernService userConcernService;
	private Article article;
	private ArticleType articleType;
	private Integer pageCount = 1;
	private Users users;
	private Integer pageSize = 10;

	/**
	 * 查询所有文章结合分页
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryAllArticle")
	@Ajax(true)
	public Map<String, Object> queryArticle() {
		Map<String, Object> map = new HashMap<String, Object>();
		int totalRows = articleService.queryArticleTotal();
		int totalPage = getTotalPage(totalRows);
		List<QuestionFrom> list = articleService.qurryPagingArticle((getPageCount() - 1) * getPageSize(),
				getPageSize());
		map.put("totalPage", totalPage);
		map.put("pageCount", getPageCount());
		map.put("pageSize", getPageSize());
		map.put("prePage", getPageCount() - 1);
		int nextPage = getPageCount() + 1;
		map.put("nextPage", totalPage < nextPage ? 0 : nextPage);
		map.put("row", list);
		return map;
		
	}

	/**
	 * 增加文章
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("addArticle")
	@Ajax(true)
	public Map<String, Object> addArticle() {
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取全局变量
		javax.servlet.http.HttpSession session = ApplicationContext.getSession();
		// Enumeration<String> names = session.getAttributeNames();
		if (session.getAttribute("users.userId") != null) {
			Integer userId = (Integer) session.getAttribute("users.userId");
			article.setUserId(userId);
		}
		article.setArticleType(1);
		article.setReleaseTime(new Timestamp(new Date().getTime()));
		try {
			boolean result = articleService.addArticle(article);
			map.put("result", result);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("errorMsg", e.getMessage());
		}
		return map;
	}

	/**
	 * 通过文章类型父ID查询出文章类型
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryArticleType")
	@Ajax(true)
	public List<ArticleType> queryArticleType() {
		return articleService.queryArticleTypeBySubID(articleType.getArticleSubTypeId());
	}

	/**
	 * 根据文章id查询文章详情
	 *
	 * @return {@link Map}<{@link String},{@link Object}> 查询成功返回 article 失败返回
	 *         null
	 */
	@RequestMapping("queryArticleDeatils")
	@Ajax(true)
	public Map<String, Object> queryArticleDeatils() {
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取全局变量
		javax.servlet.http.HttpSession session = ApplicationContext.getSession();
		Integer userId;
		try {
			Article art = articleService.queryArticleByArticleId(article.getArticleId());
			map.put("article", art);
			Users user = usersService.queryUserDetails(art.getUserId());
			map.put("userName", user.getUserName());
			map.put("userPhoto", user.getUserPhoto());
			map.put("userAutograph", user.getUserAutograph());
			map.put("userCercened", userConcernService.qurryUserConcernTotal(art.getUserId()));
			map.put("userCercen", userConcernService.qurryUserConcernTotalByUserId(art.getUserId()));
			if (session.getAttribute("users.userId") != null) {
				userId = (Integer) session.getAttribute("users.userId");
				map.put("isAddUserConcern", userConcernService.isAddUserConcern(userId, art.getUserId()));
			}
			return map;
		} catch (EmptyResultDataAccessException e) {

		}
		return null;
	}

	/**
	 * 查询页数
	 * 
	 * @param totalRows
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	public int getTotalPage(int totalRows) {
		int totalPage = totalRows / getPageSize();
		if (totalRows % getPageSize() > 0) {
			totalPage++;
		}
		return totalPage;
	}

	/**
	 * 查询第几页
	 * 
	 * @return {@link Integer}
	 */
	public Integer getPageCount() {
		return pageCount < 1 ? 1 : pageCount;
	}

	/**
	 * 查询每页Size
	 * 
	 * @return {@link Integer}
	 */
	public Integer getPageSize() {
		return pageSize < 0 ? 10 : pageSize;
	}

	/*-------------------------------------------------------------------------*/
	/**
	 * 查询所有问题结合分页
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryAllQuestion")
	@Ajax(true)
	public Map<String, Object> queryAllQuestion() {
		Map<String, Object> map = new HashMap<String, Object>();

		int totalRows = articleService.queryQuestionTotal();
		int totalPage = getTotalPage(totalRows);
		List<QuestionFrom> list = articleService.queryQuestionByFrom((getPageCount() - 1) * getPageSize(),
				getPageSize());
		map.put("totalPage", totalPage);
		map.put("pageCount", getPageCount());
		map.put("pageSize", getPageSize());
		map.put("prePage", getPageCount() - 1);
		int nextPage = getPageCount() + 1;
		map.put("nextPage", totalPage < nextPage ? 0 : nextPage);
		map.put("row", list);
		return map;
	}

	/**
	 * 根据问题id查询问题详情
	 *
	 * @return {@link Map}<{@link String},{@link Object}> 查询成功返回 article 失败返回
	 *         null
	 */
	@RequestMapping("queryQuestionDeatils")
	@Ajax(true)
	public Map<String, Object> queryQuestionDeatils() {
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取全局变量
		javax.servlet.http.HttpSession session = ApplicationContext.getSession();
		Integer userId;

		try {
			Article art = articleService.queryArticleByArticleId(article.getArticleId());
			map.put("article", art);
			Users user = usersService.queryUserDetails(art.getUserId());
			map.put("userName", user.getUserName());
			map.put("userPhoto", user.getUserPhoto());
			map.put("userAutograph", user.getUserAutograph());
			map.put("userCercened", userConcernService.qurryUserConcernTotal(art.getUserId()));
			map.put("userCercen", userConcernService.qurryUserConcernTotalByUserId(art.getUserId()));
			if (session.getAttribute("users.userId") != null) {
				
				userId = (Integer) session.getAttribute("users.userId");
				map.put("isAddUserConcern", userConcernService.isAddUserConcern(userId, art.getUserId()));
			}
			return map;
		} catch (EmptyResultDataAccessException e) {

		}
		return null;
	}

	/**
	 * 增加问题
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("addQuestion")
	@Ajax(true)
	public Map<String, Object> addQuestion() {
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取全局变量
		javax.servlet.http.HttpSession session = ApplicationContext.getSession();
		if (session.getAttribute("users.userId") != null) {
			Integer userId = (Integer) session.getAttribute("users.userId");
			article.setUserId(userId);
		}
		article.setArticleType(2);
		article.setReleaseTime(new Timestamp(new Date().getTime()));
		try {
			boolean result = articleService.addArticle(article);
			map.put("result", result);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("errorMsg", e.getMessage());
		}
		return map;
	}

	/*-------------------------------------------------------------------------*/

	/**
	 * 查询10篇文章
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryTenArticle")
	@Ajax(true)
	public Map<String, Object> queryTenArticle() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("article", articleService.queryTenArticle());
		return map;
	}

	/**
	 * 根据用户id查询该用户所有提问
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryAllQuestionById")
	@Ajax(true)
	public Map<String, Object> queryAllQuestionById() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("article", articleService.queryAllQuestionById(users.getUserId()));
		return map;
	}

	/**
	 * 根据用户id查询该用户所有文章
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryAllArticleById")
	@Ajax(true)
	public Map<String, Object> queryAllArtcleById() {
		Map<String, Object> map = new HashMap<String, Object>();

		int totalRows = articleService.queryQuestionTotal();
		int totalPage = getTotalPage(totalRows);
		List<Article> list = articleService.queryAllArticleById(users.getUserId(), (getPageCount() - 1) * getPageSize(),
				getPageSize());
		map.put("totalPage", totalPage);
		map.put("pageCount", getPageCount());
		map.put("pageSize", getPageSize());
		map.put("prePage", getPageCount() - 1);
		int nextPage = getPageCount() + 1;
		map.put("nextPage", totalPage < nextPage ? 0 : nextPage);
		map.put("row", list);
		return map;
	}

	/**
	 * 根据文章id删除该文章
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("delectArticleById")
	@Ajax(true)
	public Map<String, Object> delectArticleById() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", articleService.delectArticleById(article.getArticleId()));
		return map;
	}

	/**
	 * 根据问题id删除该问题
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("delectQuestionById")
	@Ajax(true)
	public Map<String, Object> delectQuestionById() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", articleService.delectQuestionById(article.getArticleId()));
		return map;
	}

	/**
	 * 根据文章名查文章
	 * 
	 * @param articleTitle
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryArticleByName")
	@Ajax(true)
	public Map<String, Object> queryArticleByName() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", articleService.queryArticleByName(article.getArticleTitle()));
		return map;
	}

	/**
	 * 查询所有问题
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("queryQuestion")
	@Ajax(true)
	public Map<String, Object> queryQuestion() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<QuestionFrom> list = articleService.queryQuestionByFrom((getPageCount() - 1) * getPageSize(),
				getPageSize());
		map.put("code", 0);
		map.put("msg", "success");
		map.put("count", list.size());
		map.put("data", list);
		return map;
	}

	/**
	 * 发布问题扣除用户积分
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("reduceUserInteral")
	@Ajax(true)
	public Map<String, Object> reduceUserInteral() {
		int Interal = article.getInteral();
		Map<String, Object> map = new HashMap<String, Object>();
		javax.servlet.http.HttpSession session = ApplicationContext.getSession();
		if (session.getAttribute("users.userId") != null) {
			Integer userId = (Integer) session.getAttribute("users.userId");
			map.put("result", usersService.addQuestionUpdateIntegral(Interal, userId));
		}
		return map;
	}

	/**
	 * 判断用户是否有足够积分
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("isHaveEnoughIntegral")
	@Ajax(true)
	public Map<String, Object> isHaveEnoughIntegral() {
		Map<String, Object> map = new HashMap<String, Object>();
		javax.servlet.http.HttpSession session = ApplicationContext.getSession();
		if (session.getAttribute("users.userId") != null) {
			Integer userId = (Integer) session.getAttribute("users.userId");
			map.put("result", usersService.isHaveEnoughIntegral(article.getInteral(), userId));
		}
		return map;
	}

	/**
	 * 更改问题状态为解决
	 * 
	 * @return {@link Map}<{@link String},{@link Object}>
	 */
	@RequestMapping("updateQuestionState")
	@Ajax(true)
	public Map<String, Object> updateQuestionState() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", articleService.updateQuestionState(article.getArticleId()));
		return map;
	}

	/**
	 * 判断是否可以采纳评论
	 * 
	 * @param questionId
	 * @return question_state = 0 已解决 true question_state = 1 为解决 true
	 */
	@RequestMapping("isCanAgree")
	@Ajax(true)
	public Map<String, Object> isCanAgree() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", articleService.isCanAgree(article.getArticleId()));
		return map;
	}

	/**
	 * 修改文章状态
	 * 
	 * @return
	 */
	@RequestMapping("updateArticleState")
	@Ajax(true)
	public Map<String, Object> updateArticleState() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", articleService.updateArticleState(article.getArticleId()));
		System.out.println(article.getArticleState());
		return map;
	}

	/**
	 * 根据问题标题模糊查询问题结合分页
	 * 
	 * @return
	 */
	@RequestMapping("queryQusetionByTitleLimit")
	@Ajax(true)
	public Map<String, Object> queryQuestionByTitle() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Article> list = articleService.queryQusetionByTitleLimit(article.getArticleTitle(),
				(getPageCount() - 1) * getPageSize(), getPageSize());
		map.put("code", 0);
		map.put("msg", "success");
		map.put("count", list.size());
		map.put("data", list);
		return map;
	}

	/**
	 * 根据文章标题模糊查询文章结合分页
	 * 
	 * @return
	 */
	@RequestMapping("queryArticle")
	@Ajax(true)
	public Map<String, Object> queryAllArticle() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Article> list = articleService.queryArticleByTitleLimit(article.getArticleTitle(),
				(getPageCount() - 1) * getPageSize(), getPageSize());
		map.put("code", 0);
		map.put("msg", "success");
		map.put("count", list.size());
		map.put("data", list);
		return map;
	}

}
